package com.eldos.ownerinfo;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class OwnerInfoDetails extends Activity {
    private String ownerName = "";
    private String ownerInfo = "";
    private String phoneNumber ="";
    private String email ="";
    private String smsNumber ="";

	public boolean isPhone() throws NullPointerException
	{
		PackageManager packageManager = this.getPackageManager();
		boolean phone = (packageManager != null && ((packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_GSM) || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA))));
		if (!phone)
		{
			TelephonyManager tm=(TelephonyManager ) this.getSystemService(Context.TELEPHONY_SERVICE);
			phone = (tm != null) && (tm.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN);
		}
		return phone;
	}

	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= 5)
        {
        	//getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        	getWindow().addFlags(0x00080000);
        }

        setContentView(R.layout.ownerinfowidget_details);

        loadInfo();

        // adjust item visibility
        if (ownerInfo.length() == 0)
        {
        	findViewById(R.id.textDetailsCaption).setVisibility(View.GONE);
        	findViewById(R.id.textDetailed).setVisibility(View.GONE);
        }

		boolean phone = isPhone();

        Button btnCall = (Button) findViewById(R.id.btnCall);
        Button btnSMS = (Button) findViewById(R.id.btnSMS);
        Button btnEMail = (Button) findViewById(R.id.btnEMail);

        if (phone == false || phoneNumber.length() == 0)
        {
        	btnCall.setVisibility(View.GONE);
        }
        else
        	btnCall.setOnClickListener(mCallListener);

        if (phone == false || smsNumber.length() == 0)
        {
        	btnSMS.setVisibility(View.GONE);
        }
        else
        	btnSMS.setOnClickListener(mSMSListener);

        if (email.length() == 0)
        {
        	btnEMail.setVisibility(View.GONE);
        }
        else
        	btnEMail.setOnClickListener(mEMailListener);

    }

	void loadInfo()
	{
        // read the preferences
        SharedPreferences settings = null;

    	// Bug alert: the call to getDefaultSharedPreferences will crash the application
    	// if preferences have not been created beforehand
    	try
    	{
    		settings = PreferenceManager.getDefaultSharedPreferences(getApplication().getApplicationContext());
    	}
    	catch (Exception x)
    	{
    		// just suppress the crash
    	}

    	if (settings != null)
    	{
    		ownerName = settings.getString(OwnerInfoConst.settingOwnerName, "");
    		ownerInfo = settings.getString(OwnerInfoConst.settingDetailsText, "");
	    	phoneNumber = settings.getString(OwnerInfoConst.settingPhoneNumber , "");
	    	smsNumber = settings.getString(OwnerInfoConst.settingSMSNumber, "");
	    	email = settings.getString(OwnerInfoConst.settingEMail, "");
    	}

    	// adjust item visibility and contents
        TextView textOwnerName = (TextView) findViewById(R.id.textOwnerName);
        if (ownerName.length() == 0)
        	textOwnerName.setText(getString(R.string.nameNotSpecified));
        else
        	textOwnerName.setText(ownerName);

    	TextView textDetailsBody = (TextView) findViewById(R.id.textDetailed);
        if (ownerInfo.length() != 0)
        	textDetailsBody.setText(ownerInfo);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.details_menu, menu);
	    return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
		if (item.getItemId() == R.id.menu_settings) {
			showSettingsDialog();
			return true;
	    }
		else
			return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == 25 && resultCode == RESULT_OK)
			loadInfo();
		super.onActivityResult(requestCode, resultCode, data);
	}

	void showSettingsDialog()
	{
		//Boolean b = (this.getParent() != null);
		//Toast.makeText(getBaseContext(), "parent is " + b.toString(),
        //        Toast.LENGTH_LONG).show();
		Intent intent = new Intent(this, OwnerInfoWidgetConfigure.class);
		startActivityForResult(intent, 25);
	}

    OnClickListener mCallListener = new OnClickListener() {
        public void onClick(View v) {
        	Context context = getApplicationContext();

        	//Intent intent = new Intent(Intent.ACTION_DIAL).setData(Uri.parse("tel:" + phoneNumber));
        	Intent intent = new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:" + phoneNumber));
        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            try {
            	pendingIntent.send();
            } catch (Exception e) {}
        }
    };

    OnClickListener mSMSListener = new OnClickListener() {
        public void onClick(View v) {
        	//Context context = getApplicationContext();

        	Intent intent = new Intent(OwnerInfoDetails.this, OwnerInfoSMSActivity.class);
        	///intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS );
        	startActivity(intent);


        	/*
        	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            try {
            	pendingIntent.send();
            } catch (Exception e) {}
            */
        }
    };

    OnClickListener mEMailListener = new OnClickListener() {
        public void onClick(View v) {
        	Context context = getApplicationContext();

        	Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        	//intent.setType("text/plain");
        	intent.setType("text/message");

    		String aEmailList[] = { email };
    		intent.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
    		//intent.putExtra(android.content.Intent.EXTRA_EMAIL, email);
    		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            try {
            	pendingIntent.send();
            } catch (Exception e) {}
        }
    };

}